package com.situ.mall.controller;

import com.situ.mall.config.RedisConstant;
import com.situ.mall.util.JSONResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private RedisTemplate redisTemplate;

    @ResponseBody
    @RequestMapping("/uploadImage")
    public JSONResult uploadImage(MultipartFile file) {
        System.out.println("UploadController.uploadImage");
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filename = file.getOriginalFilename();//1.jpg
        String extension = FilenameUtils.getExtension(filename);//jpg
        String newFilename = uuid + "." + extension;//82e0452ac2ab4b57801b9fc27d651a3e.jpg

        System.out.println("newFilename: " + newFilename);
        String filePath = "D:\\mypic\\" + newFilename;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将上传的图片保存到Redis中
        redisTemplate.opsForSet().add(RedisConstant.UPLOAD_IMAGE, newFilename);
        System.out.println("上传图片：" + newFilename);

        return JSONResult.ok("上传成功", newFilename);
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);//82e0452a-c2ab-4b57-801b-9fc27d651a3e
        System.out.println(uuid.replace("-", ""));//82e0452ac2ab4b57801b9fc27d651a3e
    }
}
